package com.xyy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xyy.common.PageResult;
import com.xyy.dto.AdminCreateDTO;
import com.xyy.dto.AdminQueryDTO;
import com.xyy.dto.AdminUpdateDTO;
import com.xyy.entity.Admin;
import com.xyy.mapper.AdminMapper;
import com.xyy.service.AdminService;
import com.xyy.util.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * 管理员服务实现类
 */
@Slf4j
@Service
public class AdminServiceImpl implements AdminService {

    @Autowired
    private AdminMapper adminMapper;

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    @Override
    public Admin login(String username, String password) {
        // 根据用户名查询管理员
        LambdaQueryWrapper<Admin> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Admin::getUsername, username);
        Admin admin = adminMapper.selectOne(queryWrapper);

        if (admin == null) {
            throw new RuntimeException("用户名或密码错误");
        }

        // 验证密码
        if (!passwordEncoder.matches(password, admin.getPassword())) {
            throw new RuntimeException("用户名或密码错误");
        }

        // 更新最后登录时间
        admin.setLastLoginTime(LocalDateTime.now());
        adminMapper.updateById(admin);

        return admin;
    }

    @Override
    public void createAdmin(AdminCreateDTO createDTO) {
        // 检查用户名是否已存在
        LambdaQueryWrapper<Admin> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Admin::getUsername, createDTO.getUsername());
        if (adminMapper.selectCount(queryWrapper) > 0) {
            throw new RuntimeException("用户名已存在");
        }

        // 检查手机号是否已存在
        queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Admin::getPhone, createDTO.getPhone());
        if (adminMapper.selectCount(queryWrapper) > 0) {
            throw new RuntimeException("手机号已被注册");
        }

        // 检查邮箱是否已存在
        queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Admin::getEmail, createDTO.getEmail());
        if (adminMapper.selectCount(queryWrapper) > 0) {
            throw new RuntimeException("邮箱已被注册");
        }

        // 创建管理员
        Admin admin = new Admin();
        BeanUtils.copyProperties(createDTO, admin);
        admin.setPassword(passwordEncoder.encode(createDTO.getPassword()));

        adminMapper.insert(admin);
    }

    @Override
    public void updateAdmin(AdminUpdateDTO updateDTO) {
        // 检查管理员是否存在
        Admin existingAdmin = adminMapper.selectById(updateDTO.getId());
        if (existingAdmin == null) {
            throw new RuntimeException("管理员不存在");
        }

        // 检查手机号是否被其他管理员使用
        LambdaQueryWrapper<Admin> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Admin::getPhone, updateDTO.getPhone())
                .ne(Admin::getId, updateDTO.getId());
        if (adminMapper.selectCount(queryWrapper) > 0) {
            throw new RuntimeException("手机号已被其他管理员使用");
        }

        // 检查邮箱是否被其他管理员使用
        queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Admin::getEmail, updateDTO.getEmail())
                .ne(Admin::getId, updateDTO.getId());
        if (adminMapper.selectCount(queryWrapper) > 0) {
            throw new RuntimeException("邮箱已被其他管理员使用");
        }

        // 更新管理员信息
        Admin admin = new Admin();
        BeanUtils.copyProperties(updateDTO, admin);

        adminMapper.updateById(admin);
    }

    @Override
    public void deleteAdmin(Long adminId) {
        // 检查管理员是否存在
        Admin admin = adminMapper.selectById(adminId);
        if (admin == null) {
            throw new RuntimeException("管理员不存在");
        }

        // 不能删除超级管理员
        if (admin.getLevel() == 2) {
            throw new RuntimeException("不能删除超级管理员");
        }

        adminMapper.deleteById(adminId);
    }

    @Override
    public void batchDeleteAdmin(List<Long> adminIds) {
        if (adminIds == null || adminIds.isEmpty()) {
            throw new RuntimeException("管理员ID列表不能为空");
        }

        // 检查是否包含超级管理员
        LambdaQueryWrapper<Admin> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(Admin::getId, adminIds)
                .eq(Admin::getLevel, 2);
        if (adminMapper.selectCount(queryWrapper) > 0) {
            throw new RuntimeException("不能删除超级管理员");
        }

        adminMapper.deleteBatchIds(adminIds);
    }

    @Override
    public PageResult<Admin> pageQuery(AdminQueryDTO queryDTO, Integer current, Integer size) {
        Page<Admin> page = new Page<>(current, size);
        LambdaQueryWrapper<Admin> queryWrapper = new LambdaQueryWrapper<>();

        // 添加查询条件
        if (StringUtils.hasText(queryDTO.getUsername())) {
            queryWrapper.like(Admin::getUsername, queryDTO.getUsername());
        }
        if (StringUtils.hasText(queryDTO.getRealName())) {
            queryWrapper.like(Admin::getRealName, queryDTO.getRealName());
        }
        if (StringUtils.hasText(queryDTO.getPhone())) {
            queryWrapper.like(Admin::getPhone, queryDTO.getPhone());
        }
        if (StringUtils.hasText(queryDTO.getEmail())) {
            queryWrapper.like(Admin::getEmail, queryDTO.getEmail());
        }
        if (queryDTO.getLevel() != null) {
            queryWrapper.eq(Admin::getLevel, queryDTO.getLevel());
        }
        if (StringUtils.hasText(queryDTO.getStartTime())) {
            queryWrapper.ge(Admin::getCreateTime, LocalDateTime.parse(queryDTO.getStartTime() + " 00:00:00", 
                    DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        }
        if (StringUtils.hasText(queryDTO.getEndTime())) {
            queryWrapper.le(Admin::getCreateTime, LocalDateTime.parse(queryDTO.getEndTime() + " 23:59:59", 
                    DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        }

        // 按创建时间倒序
        queryWrapper.orderByDesc(Admin::getCreateTime);

        IPage<Admin> pageResult = adminMapper.selectPage(page, queryWrapper);

        return new PageResult<>(
                pageResult.getRecords(),
                pageResult.getTotal(),
                pageResult.getCurrent(),
                pageResult.getSize()
        );
    }

    @Override
    public Admin getAdminById(Long adminId) {
        return adminMapper.selectById(adminId);
    }

    @Override
    public List<Admin> getAllAdmins() {
        LambdaQueryWrapper<Admin> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(Admin::getCreateTime);
        return adminMapper.selectList(queryWrapper);
    }

    @Override
    public Admin getAdminByUsername(String username) {
        LambdaQueryWrapper<Admin> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Admin::getUsername, username);
        return adminMapper.selectOne(queryWrapper);
    }
} 